package com.peng.herostory.mq;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;

@Slf4j
public final class MqProducer {
    private static MqProducer instance = new MqProducer();
    private static DefaultMQProducer producer;

    private MqProducer() {

    }

    public static MqProducer getInstance() {
        return instance;
    }

    public static void init() {
        try {
            producer = new DefaultMQProducer("herostory");
            producer.setNamesrvAddr("192.168.221.66:9876");
            producer.start();
            producer.setRetryTimesWhenSendAsyncFailed(3);


        } catch (Exception ex) {
            log.error("e:{1}", ex);
        }

    }

    public void sendMsg(String topic, Object msg) {
        if (null == topic ||
                null == msg) {
            return;
        }

        if (null == producer) {
            throw new RuntimeException("_producer 尚未初始化");
        }
        Message message = new Message();
        message.setTopic(topic);
        message.setBody(JSONObject.toJSONBytes(msg));
        try {
            log.info("准备发送一条消息 topic:{}  ,body：{}", topic, msg);
            producer.send(message);
        } catch (Exception ex) {
            log.error("e:{0}", ex);
        }
    }
}
